﻿#include "mainwindow.h"
#include <QVBoxLayout>
#include <QThread>

// 初始化共享资源和互斥锁
int sharedCounter = 0;
QMutex mutex;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    // 创建界面元素
    startButton = new QPushButton("Start Threads", this);
    statusLabel = new QLabel("Status: Waiting", this);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(startButton);
    layout->addWidget(statusLabel);

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(layout);
    setCentralWidget(centralWidget);

    // 连接按钮点击信号到槽函数
    connect(startButton, &QPushButton::clicked, this, &MainWindow::startThreads);
}

MainWindow::~MainWindow()
{
    for (auto thread : threads) {
        thread->quit();
        thread->wait();
        delete thread;
    }
}

void MainWindow::startThreads()
{
    if (!threads.isEmpty()) return;

    // 启动两个工作线程
    for (int i = 0; i < 2; ++i) {
        WorkerThread *thread = new WorkerThread(i + 1, this);
        threads.append(thread);
        connect(thread, &WorkerThread::counterUpdated, this, &MainWindow::updateStatus);
        thread->start();
    }
}

void MainWindow::updateStatus(int threadId, int value)
{
    statusLabel->setText(QString("Thread %1 updated counter to %2").arg(threadId).arg(value));
}


void WorkerThread::run()
{
    for (int i = 0; i < 10; ++i) {
        // 加锁保护共享资源
        mutex.lock();

        // 访问并修改共享计数器
        sharedCounter += 1;
        emit counterUpdated(threadId, sharedCounter);

        // 释放锁
        mutex.unlock();

        QThread::msleep(500); // 模拟工作延迟
    }
}
